package com.huacai.merchant.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.huacai.common.core.domain.entity.SysUser;
import com.huacai.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.huacai.common.annotation.Log;
import com.huacai.common.core.controller.BaseController;
import com.huacai.common.core.domain.AjaxResult;
import com.huacai.common.enums.BusinessType;
import java.io.InputStream;
import org.springframework.web.multipart.MultipartFile;
import com.huacai.merchant.domain.Merchant;
import com.huacai.merchant.service.IMerchantService;
import com.huacai.common.utils.poi.ExcelUtil;
import com.huacai.common.core.page.TableDataInfo;

import static sun.management.snmp.jvminstr.JvmThreadInstanceEntryImpl.ThreadStateMap.setState;

/**
 * 商家Controller
 *
 * @author hsj
 * @date 2025-05-12
 */
@RestController
@RequestMapping("/huacai/merchant")
public class MerchantController extends BaseController
{
    @Autowired
    private IMerchantService merchantService;

    @Autowired
    private ISysUserService sysUserService;



    /**
     * 查询商家列表
     */
//    @PreAuthorize("@ss.hasPermi('huacai:merchant:list')")
    @GetMapping("/list")
    public TableDataInfo list(Merchant merchant)
    {
        startPage();
        List<Merchant> list = merchantService.selectMerchantList(merchant);
        return getDataTable(list);
    }

    /**
     * 导出商家列表
     */
//    @PreAuthorize("@ss.hasPermi('huacai:merchant:export')")
    @Log(title = "商家", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Merchant merchant)
    {
        List<Merchant> list = merchantService.selectMerchantList(merchant);
        ExcelUtil<Merchant> util = new ExcelUtil<Merchant>(Merchant.class);
        util.exportExcel(response, list, "商家数据");
    }

    /**
     * 下载模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<Merchant> util = new ExcelUtil<Merchant>(Merchant.class);
        util.importTemplateExcel(response, "商家数据");
    }

    /**
     * 导入数据
     */
    @Log(title = "商家", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('huacai:merchant:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        ExcelUtil<Merchant> util = new ExcelUtil<Merchant>(Merchant.class);
        InputStream inputStream = file.getInputStream();
        List<Merchant> list = util.importExcel(inputStream );
        inputStream.close();
        int count = merchantService.batchInsertMerchant(list);
        return AjaxResult.success("导入成功" + count + "条信息！");
    }

    /**
     * 获取商家详细信息
     */
//    @PreAuthorize("@ss.hasPermi('huacai:merchant:query')")
    @GetMapping(value = "/{merchantId}")
    public AjaxResult getInfo(@PathVariable("merchantId") String merchantId)
    {
        return success(merchantService.selectMerchantByMerchantId(merchantId));
    }

    /**
     * 新增商家
     */
//    @PreAuthorize("@ss.hasPermi('huacai:merchant:add')")
    @Log(title = "商家", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Merchant merchant)
    {
        return toAjax(merchantService.insertMerchant(merchant));
    }

    /**
     * 修改商家
     */
    @Log(title = "商家", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Merchant merchant)
    {
        return toAjax(merchantService.updateMerchant(merchant));
    }

    /**
     * 删除商家
     */
//    @PreAuthorize("@ss.hasPermi('huacai:merchant:remove')")
    @Log(title = "商家", businessType = BusinessType.DELETE)
	@DeleteMapping("/{merchantIds}")
    public AjaxResult remove(@PathVariable String[] merchantIds)
    {
        return toAjax(merchantService.deleteMerchantByMerchantIds(merchantIds));
    }

    /**
     * 查询商家表当中是否存在某个userId
     */
//    @PreAuthorize("@ss.hasPermi('huacai:merchant:query')")
    @GetMapping("/selectMerchantWhereUserId")
    public AjaxResult selectMerchantWhereUserId()
    {
//        获取当前用户登录的用户ID
        Integer userId=Math.toIntExact(getUserId());
        Integer selectMerchantWhereUserId=merchantService.selectMerchantWhereUserId(userId);
        System.out.println(selectMerchantWhereUserId);
        if(selectMerchantWhereUserId == 0){
            return success(false);
        }else {
            return success(true);
        }
    }


    /**
     * 根据userId查询商家信息
     */
    @GetMapping("/selectMerchantByUserId")
    public AjaxResult selectMerchantByUserId()
    {
        Integer userId=Math.toIntExact(getUserId());
        return success(merchantService.selectMerchantByUserId(userId));
    }

    /**
     * 审核通过
     */
    @Log(title = "商家", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/{merchantId}")
    public AjaxResult approved(@PathVariable String merchantId)
    {
        //根据商家ID查询商家信息
        Merchant byMerchant = merchantService.selectMerchantByMerchantId(merchantId);
        //获取该商家的UserID
        Integer merUserId = byMerchant.getUserId();
//        System.out.println(merUserId);
        //创建用户实体类
        SysUser merUser = new SysUser();
        //插入商家的UserID
        merUser.setUserId(Long.valueOf(merUserId));
        //创建角色为商家的角色ID
        Long[] roleIds={7L};
        //插入角色ID
        merUser.setRoleIds(roleIds);
        //调用方法修改用户方法sysUserService
        sysUserService.updateUser(merUser);
        //创建商家实体类
        Merchant merchant = new Merchant();
        //插入商家ID
        merchant.setMerchantId(merchantId);
//        将该商家的认证状态改为已通过
        merchant.setState("已通过");
//        调用修改商家方法
        return toAjax(merchantService.updateMerchant(merchant));
    }


}
